<script setup lang="ts">
import type {
  SysUserPasswordQo,
} from '#/system/user'
import { updateSysUserPasswordApi } from '@/api/system/user'

const formRef = $ref<FormInstance>()

const formState = $ref<SysUserPasswordQo>({
  password: '',
  confirmPassword: '',
})

const rules = reactive<FormRules<SysUserPasswordQo>>({
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' },
  ],
  confirmPassword: [
    { required: true, message: '请输入确认密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' },
    { validator: validatePassword, trigger: 'blur' },
  ],
})

function validatePassword(rule: any, value: string, callback: any) {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  }
  else if (value !== formState.password) {
    callback(new Error('两次输入密码不一致'))
  }
  else {
    callback()
  }
}

async function updatePassword() {
  if (!formRef)
    return
  formRef.validate(async (valid) => {
    if (!valid)
      return
    await updateSysUserPasswordApi(formState)
    Message({
      type: 'success',
      message: '修改成功',
    })
  })
}
</script>

<template>
  <el-form
    ref="formRef"
    :model="formState"
    :rules="rules"
    label-width="80px"
    label-position="left"
  >
    <el-form-item prop="password" label="新密码">
      <el-input
        v-model="formState.password"
        placeholder="请输入新密码"
        show-password
        type="password"
      />
    </el-form-item>
    <el-form-item prop="confirmPassword" label="确认密码">
      <el-input
        v-model="formState.confirmPassword"
        placeholder="请输入确认密码"
        show-password
        type="password"
      />
    </el-form-item>
    <div un-flex="~ justify-end">
      <el-button type="primary" @click="updatePassword">
        提交
      </el-button>
    </div>
  </el-form>
</template>

<style scoped></style>
